package com.javaboy.vhr.service.impl;

import com.javaboy.vhr.mapper.MenuMapper;
import com.javaboy.vhr.entity.Hr;
import com.javaboy.vhr.entity.Menu;
import com.javaboy.vhr.mapper.MenuRoleMapper;
import com.javaboy.vhr.service.MenuService;
import com.javaboy.vhr.utils.HrUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * (Menu)表服务实现类
 *
 * @author gaoyang
 * @since 2020-10-31 14:52:42
 */
@Service("menuService")
public class MenuServiceImpl implements MenuService {
    @Resource
    private MenuMapper menuDao;
    @Resource
    private MenuRoleMapper menuRoleMapper;

    @Override
    public List<Menu> getMenusByHrId() {
        return this.menuDao.getMenusByHrId(HrUtil.getCurrentHr().getId());
    }

    @Override
    public Menu queryById(Integer id) {
        return this.menuDao.queryById(id);
    }

    @Override
    public List<Menu> queryAll() {
        List<Menu> menuList = this.menuDao.queryAll(new Menu());
        List<Menu> menuTree = new ArrayList<>();
        menuList.forEach(menu -> {
            // 判断是否为顶层节点
            if (menu.getParentId() == null) {
                // 获取子节点
                menu.setChildren(this.getChildTree(menu.getId(), menuList));
                menuTree.add(menu);
            }
        });
        return menuTree;
    }

    @Override
    public List<Menu> getAllMenusWithRole() {
        return this.menuDao.getAllMenusWithRole();
    }

    @Override
    public List<Menu> getAllMenus() {
        return this.menuDao.getAllMenus();
    }

    @Override
    public Boolean updateMenuRole(Integer rid, Integer[] mids) {
        this.menuRoleMapper.deleteByRid(rid);
        if (mids == null || mids.length == 0) {
            return true;
        }
        Integer result = menuRoleMapper.insertRecord(rid, mids);
        return result==mids.length;
    }

    @Override
    public List<Integer> getMidsByRid(Integer rid) {
        return this.menuRoleMapper.getMidsByRid(rid);
    }

    private List<Menu> getChildTree(Integer id, List<Menu> menuList) {
        List<Menu> childList = new ArrayList<>();
        // 循环获取子节点
        menuList.forEach(menu -> {
            if (menu.getParentId() != null){
                if (menu.getParentId().equals(id)) {
                    childList.add(menu);
                }
            }
        });
        // 获取子节点的子节点
        childList.forEach(menu -> {
            // 递归获取子节点
            List<Menu> childTree = this.getChildTree(menu.getId(), menuList);
            if (childTree.size() > 0) {
                menu.setChildren(childTree);
            }
        });
        return childList;
    }


}